import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'constants.dart';

void main() {
  runApp(ForgotPasswordPage());
}

class ForgotPasswordPage extends StatefulWidget {
  @override
  _ForgotPasswordPageState createState() => _ForgotPasswordPageState();
}

class _ForgotPasswordPageState extends State<ForgotPasswordPage> {
  TextEditingController _phoneController = TextEditingController();
  TextEditingController _passwordController = TextEditingController();
  TextEditingController _smsController = TextEditingController();
  final String serverUrl = AppConstants.serverUrl;
  bool _obscureText = true;

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          backgroundColor: Colors.white,
          centerTitle: true,
          title: Text(
            '忘记密码',
            style: TextStyle(fontSize: 20, color: Colors.black),
          ),
          leading: IconButton(
            icon: Icon(
              Icons.arrow_back,
              color: Colors.black54,
            ),
            onPressed: () {
              Navigator.pop(context);
            },
          ),
        ),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              SizedBox(height: 20.0),
              buildTextField(_phoneController, '请输入手机号'),
              SizedBox(height: 10.0),
              buildPasswordTextField(_passwordController, '请设置密码'),
              SizedBox(height: 10.0),
              buildTextField(_smsController, '请输入验证码'),
              SizedBox(height: 20.0),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                children: <Widget>[
                  buildElevatedButton('重置密码', resetPassword),
                  buildElevatedButton('获取验证码', getSMS),
                ],
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget buildTextField(TextEditingController controller, String hintText) {
    return Container(
      width: 250.0,
      padding: EdgeInsets.symmetric(horizontal: 20.0),
      decoration: BoxDecoration(
        border: Border.all(color: Color.fromARGB(255, 179, 202, 193)),
        borderRadius: BorderRadius.circular(10.0),
        color: Colors.white,
      ),
      child: TextField(
        controller: controller,
        decoration: InputDecoration(
          hintText: hintText,
          border: InputBorder.none,
        ),
      ),
    );
  }

  Widget buildPasswordTextField(
      TextEditingController controller, String hintText) {
    return Container(
      width: 250.0,
      padding: EdgeInsets.symmetric(horizontal: 20.0),
      decoration: BoxDecoration(
        border: Border.all(color: Color.fromARGB(255, 179, 202, 193)),
        borderRadius: BorderRadius.circular(10.0),
        color: Colors.white,
      ),
      child: TextField(
        controller: controller,
        decoration: InputDecoration(
          hintText: hintText,
          border: InputBorder.none,
          suffixIcon: GestureDetector(
            onTap: () {
              setState(() {
                _obscureText = !_obscureText;
              });
            },
            child: Icon(
              _obscureText ? Icons.visibility : Icons.visibility_off,
            ),
          ),
        ),
        obscureText: _obscureText,
      ),
    );
  }

  Widget buildElevatedButton(String label, Function() onPressed) {
    return ElevatedButton(
      onPressed: onPressed,
      child: Text(label),
      style: ButtonStyle(
        backgroundColor: MaterialStateProperty.all<Color>(
            Color.fromARGB(255, 179, 202, 193)),
        minimumSize: MaterialStateProperty.all<Size>(Size(10, 40)),
      ),
    );
  }

  void resetPassword() async {
    final phone = _phoneController.text;
    final password = _passwordController.text;
    final sms = _smsController.text;

    if (phone.isEmpty || password.isEmpty || sms.isEmpty) {
      showErrorDialog('错误', '请填写所有字段');
      return;
    }

    final requestData = {
      'phone': phone,
      'password': password,
      'sms': sms,
    };
    final header = {'Content-Type': 'application/json'};

    try {
      final Uri uri = Uri.parse('$serverUrl/v1/resetPassword');
      final response = await http.post(
        uri,
        headers: header,
        body: jsonEncode(requestData),
      );
      final responseBody = response.body;
      if (response.statusCode == 200) {
        showSuccessDialog('重置成功', '您已成功重置密码。');
      } else if (response.statusCode == 400) {
        showErrorDialog('重置失败', '验证码错误，请重新输入。');
      } else {
        showErrorDialog('重置失败', '重置失败，请稍后重试。');
      }
    } catch (e) {
      showErrorDialog('错误', '发生了一个错误，请稍后重试。');
      print(e);
    }
  }

  void showErrorDialog(String title, String content) {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return buildAlertDialog(title, content);
      },
    );
  }

  void showSuccessDialog(String title, String content) {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return buildAlertDialog(title, content);
      },
    );
  }

  AlertDialog buildAlertDialog(String title, String content) {
    return AlertDialog(
      title: Text(title),
      content: Text(content),
      actions: [
        TextButton(
          child: Text('确定'),
          onPressed: () {
            Navigator.of(context).pop();
          },
        ),
      ],
    );
  }

  void getSMS() async {
    final phone = _phoneController.text;

    if (phone.isEmpty) {
      showErrorDialog('错误', '请输入手机号');
      return;
    }

    final requestData = {
      'phone': phone,
    };

    try {
      final Uri uri = Uri.parse('$serverUrl/v1/getSMSCode?phone=$phone');
      final response = await http.get(uri);
      if (response.statusCode == 200) {
        showDialog(
          context: context,
          builder: (BuildContext context) {
            return AlertDialog(
              title: Text('获取验证码成功'),
              content: Text('验证码已发送，请注意查收。'),
              actions: [
                TextButton(
                  child: Text('确定'),
                  onPressed: () {
                    Navigator.of(context).pop();
                  },
                ),
              ],
            );
          },
        );
      } else {
        showErrorDialog('获取验证码失败', '获取验证码失败，请稍后重试。');
      }
    } catch (e) {
      showErrorDialog('错误', '发生了一个错误，请稍后重试。');
    }
  }

  @override
  void dispose() {
    _phoneController.dispose();
    _passwordController.dispose();
    _smsController.dispose();
    super.dispose();
  }
}
